import { defineStore } from "pinia";
import {reqGetShopCartList,reqGetAddShopCart,reqGetCheckCart,reqGetDeleteCart,reqGetBatchCheckCart,reqGetBatchDeleteCart} from '@/api/shopcart'
import type {CartListModel} from '@/api/model/shopCart'

export const useShopCartStore = defineStore('shopcart',{

  state(){
    return{
          shopCartList:[] as CartListModel
    }
  },
  actions:{
    //获取购物车列表数据
    async getShopCartList(){
     const res =  await reqGetShopCartList()
    //  console.log(res)
    this.shopCartList = res[0]?.cartInfoList
    },
    //添加或失去焦点后修改购物车数据
    async getAddShopCart(skuId:number,skuNum:number){
      // console.log('添加购物车数据',skuNum)
      await reqGetAddShopCart(skuId,skuNum)
      const shop = this.shopCartList.find((cart)=>cart.skuId === skuId)
         shop.skuNum += skuNum
    },
    //切换选中商品
    async updatedShop(skuId : number,isChecked:number) {
      await reqGetCheckCart(skuId,isChecked)
      this.shopCartList.find((cart)=>cart.skuId === skuId).isChecked = isChecked
      // const shop = this.shopCartList.filter((item)=>item.skuId === skuId)
      // // console.log(shop)
      //  shop.isChecked   = isChecked
    },
    //删除一条数据
    async deleteShop(skuId:number){
          await reqGetDeleteCart(skuId)
      this.shopCartList = this.shopCartList.filter((item)=>item.skuId !== skuId)
    },
    //批量选中购物车商品
  async AllisCheckCart (isChecked:number){
    // console.log(isChecked)
    const skuIdList = this.shopCartList.filter((cart)=>{
      return cart.isChecked !== isChecked
    }).map((cart)=>cart.skuId)
    await reqGetBatchCheckCart(isChecked,skuIdList)
    this.shopCartList.forEach((cart)=>{
      if(skuIdList.includes(cart.skuId)){
        cart.isChecked = isChecked
      }
    })
  },
  //批量删除
  async AllDeleteShopCart(){
    const skuIdList = this.shopCartList.filter((cart)=>cart.isChecked).map((cart)=>cart.skuId)
    await reqGetBatchDeleteCart(skuIdList)
    this.shopCartList = this.shopCartList.filter((cart)=>!cart.isChecked)
  }
  },

  getters:{
    //选中数量
    ischeckedNumber(state){
      //当前已勾选的商品
      return state.shopCartList?.reduce((p,c)=>{
        //强制将boolean类型转为number
        // let isChecked : number = Number(c.isChecked)
        return p + (c.isChecked  ? c.skuNum :0)
      },0) || 0
    },
    //商品总价
    shopAllPrice(state){
      //当前一勾选商品的总价
      return state.shopCartList?.reduce((p,c)=>{
        // let isChecked : number = Number(c.isChecked)
        return p + (c.isChecked*c.skuPrice*c.skuNum)
      },0) || 0
    },
    //全选
    isAllChecked(state){
      //没有长度直接return
      if(state.shopCartList?.length <= 0) return
      return state.shopCartList?.every((cart)=>cart.isChecked)
    },
  }
})
